package com.example.springsecuritydemo.handler;

import com.example.springsecuritydemo.support.UserContext;
import com.example.springsecuritydemo.utils.JWTTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author by linenxi
 * @Classname LoginSuccessHandler
 * @Description
 * @Date 2019/5/10
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JWTTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        UserContext.User user = new UserContext().new User();
        user.setUserAccount("13587872968");
        user.setUserId(1);
        user.setUserName("linenxi");
        response.getWriter().write(objectMapper.writeValueAsString(jwtTokenUtil.generateToken(user)));
    }
}
